"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  baseURL: process.env.VUE_APP_BASE_API
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    // 从 localStorage 中获取 JWT 令牌
    const token = localStorage.getItem('token');
    if (token) {
      // 将 JWT 令牌添加到请求头中
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response.data;
  },

    (error) => {
      if (error.response && error.response.status === 401) {
        console.error('未授权访问，返回 401 状态码');
        // 可以在这里跳转到登录页面或显示错误信息
        alert('您未登录或登录信息已过期，请重新登录。');
        // 跳转到登录页面
        window.location.href = '/login';
      }
      return Promise.reject(error);
    }
  // function(error) {
  //   // Do something with response error
  //   return Promise.reject(error);
  // }
);

Plugin.install = function(Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
export {_axios as request} //导出变量给其他模块使用